// PotatoeServerThread.cc
// author: CASO-04

#include "PotatoeServerThread.h"
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <sstream>		// int to string

namespace PracticaCaso
{
	PotatoeServerThread::~PotatoeServerThread()
	{
		delete this->client;
	}

	void PotatoeServerThread::run()
	{
		string pregunta;
		int solucion;
		string respuesta;
		int numRespuesta;
		int intentos = 0;

		// Get the question and answer
		srand (time(NULL));
		int random = rand() % 3;
		switch (random)
		{
		case 0:
			pregunta = "¿Cuántos km hay de la Tierra a la Luna?";
			solucion = 384400;
			break;
		case 1:
			pregunta = "¿En qué año ocurrió la Revolución Francesa?";
			solucion = 1789;
			break;
		case 2:
			pregunta = "¿En qué año nació Alan Turing?";
			solucion = 1912;
			break;
		default:
			(this->client)->close();
			break;
		}

		// Send the question
		string msg = (this->client)->receive();
		cout << "Message received: " << msg << endl;
		(this->client)->send(pregunta);
		cout << "Message sent: " << pregunta << endl;

		// While not end
		bool fin = false;
		while (!fin)
		{
			// Get the answer
			string msg = (this->client)->receive();
			cout << "Message received: " << msg << endl;
			numRespuesta = atoi(msg.c_str());
			
			// Increment the counter
			intentos++;

			// Process the answer
			if (numRespuesta > solucion)
			{
				msg = "¡MENOS!";
				(this->client)->send(msg);
				cout << "Message sent: " << msg << endl;
			}
			else if (numRespuesta < solucion)
			{
				msg = "¡MÁS!";
				(this->client)->send(msg);
				cout << "Message sent: " << msg << endl;
			}
			else
			{
				msg = "ACERTASTE! Has necesidado " + static_cast<ostringstream*>( &(ostringstream() << intentos ) )->str() + " intentos.";
				(this->client)->send(msg);
				cout << "Message sent: " << msg << endl;
				fin = true;
			}
		}
		// End connection
		(this->client)->close();
	}
}
